<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加产品</el-button>

    <!-- 产品表格 -->
    <el-table :data="products" style="width: 100%" border>
      <el-table-column prop="ProductName" label="产品名称" />
      <el-table-column prop="Category.CategoryName" label="分类" />
      <el-table-column prop="Price" label="价格" />
      <el-table-column label="图片">
        <template #default="{ row }">
          <img :src="row.ImageURL" alt="产品图片" style="height: 50px;">
        </template>
      </el-table-column>
      <el-table-column prop="IsAvailable" label="是否上架">
        <template #default="{ row }">
          {{ row.IsAvailable ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="editProduct(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(row.ProductID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑产品' : '添加产品'">
      <el-form :model="form" label-width="100px">

        <el-form-item label="产品名称">
          <el-input v-model="form.ProductName" />
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="form.CategoryID" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.CategoryID"
              :label="category.CategoryName"
              :value="category.CategoryID"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="价格">
          <el-input v-model.number="form.Price" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="form.Description" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="图片地址">
          <el-input v-model="form.ImageURL" />
        </el-form-item>

        <el-form-item label="是否上架">
          <el-switch v-model="form.IsAvailable" />
        </el-form-item>

        <el-form-item label="推荐商品">
          <el-switch v-model="form.IsFeatured" />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '@/utils/http'
import { ElMessage } from 'element-plus'

const products = ref([])
const categories = ref([])

const dialogVisible = ref(false)
const isEditing = ref(false)
const editingId = ref(null)

const form = ref({
  ProductName: '',
  CategoryID: null,
  Price: 0,
  Description: '',
  ImageURL: '/image/img.jpg',
  IsAvailable: true,
  IsFeatured: false
})

// 获取产品列表
const fetchProducts = async () => {
  try {
    const res = await http.get('products/')
    products.value = res.data || []
  } catch (error) {
    console.error('获取产品失败:', error)
    ElMessage.error('获取产品失败')
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await http.get('productcategories') // 假设你也有分类的 API
    categories.value = res.data || []
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  form.value = {
    ProductName: '',
    CategoryID: null,
    Price: 0,
    Description: '',
    ImageURL: '/image/img.jpg',
    IsAvailable: true,
    IsFeatured: false
  }
  isEditing.value = false
  editingId.value = null
  dialogVisible.value = true
}

// 编辑产品
const editProduct = (product) => {
  form.value = {
    ProductName: product.ProductName,
    CategoryID: product.CategoryID,
    Price: product.Price,
    Description: product.Description,
    ImageURL: product.ImageURL,
    IsAvailable: product.IsAvailable,
    IsFeatured: product.IsFeatured
  }
  editingId.value = product.ProductID
  isEditing.value = true
  dialogVisible.value = true
}

// 保存产品
const saveProduct = async () => {
  if (!form.value.ProductName || !form.value.CategoryID) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    const payload = { ...form.value }

    if (editingId.value) {
      await http.put(`products/${editingId.value}/`, payload)
      ElMessage.success('更新成功')
    } else {
      await http.post('products/', payload)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    console.error('保存产品失败:', error)
    ElMessage.error('保存产品失败')
  }
}

// 删除产品
const deleteProduct = async (id) => {
  try {
    await http.delete(`products/${id}/`)
    fetchProducts()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>